package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServiceImpl implements ApBehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询文章行为数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        // 1.校验参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null || apUser.getId().equals(0)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2.查询点赞、不喜欢、收藏、关注是否有数据
        String likesKey = "USER_LIKES" + dto.getArticleId();
        String unLikeKey = "USER_UN_LIKES" + dto.getArticleId();
        String collectionKey = "USER_COLLECTION" + dto.getArticleId();
        String followKey = "USER_FOLLOW" + apUser.getId();
        Boolean likesFlag = redisTemplate.opsForHash().hasKey(likesKey, apUser.getId().toString());
        Boolean unLikeFlag = redisTemplate.opsForHash().hasKey(unLikeKey, apUser.getId().toString());
        Boolean collectionFlag = redisTemplate.opsForHash().hasKey(collectionKey, apUser.getId().toString());
        Boolean followFlag = redisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());
        // 3.封装结果返回
        Map<String, Boolean> result = new HashMap<>();
        result.put("islike", likesFlag);
        result.put("isunlike", unLikeFlag);
        result.put("iscollection", collectionFlag);
        result.put("isfollow", followFlag);
        return ResponseResult.okResult(result);
    }
}
